﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Reflection;
using System.Configuration;
using LiJu.Common;
using System.Runtime.InteropServices;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.StartPanel;

namespace LiJu
{
    public partial class Main : Form
    {

        /// <summary>
        /// 用户编号
        /// </summary>
        public string UserID { get; set; }

        /// <summary>
        /// 用户名
        /// </summary>
        public string UserName { get; set; }

        public Main()
        {
            InitializeComponent();
            OpenChildFrom("Work");

            // 加载时启用默认双缓冲并提供无闪烁的图形呈现：
            this.DoubleBuffered = true;//设置本窗体
            SetStyle(ControlStyles.UserPaint, true);
            SetStyle(ControlStyles.AllPaintingInWmPaint, true); // 禁止擦除背景.
            SetStyle(ControlStyles.DoubleBuffer, true); // 双缓冲
        }


        #region 使窗体可以移动
        //[DllImport("user32.dll")]
        //public static extern bool ReleaseCapture();
        //[DllImport("user32.dll")]
        //public static extern bool SendMessage(IntPtr hwnd, int wMsg, int wParam, int IParam);
        //public const int WM_SYSCOMMAND = 0x0112;
        //public const int SC_MOVE = 0xF010;
        //public const int HTCAPTION = 0x0002;
        #endregion

        /// <summary>
        /// 顶部panel控件设置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void panel1_MouseDown(object sender, MouseEventArgs e)
        {
            //拖动窗体
            //this.Cursor = System.Windows.Forms.Cursors.Hand;//改变鼠标样式
            //ReleaseCapture();
            //SendMessage(this.Handle, WM_SYSCOMMAND, SC_MOVE + HTCAPTION, 0);
            //this.Cursor = System.Windows.Forms.Cursors.Default;
        }


        #region 解决控件添加背景图后闪屏问题

        /// <summary>
        /// 防止闪屏
        /// </summary>
        protected override CreateParams CreateParams
        {
            get
            {
                CreateParams cp = base.CreateParams;
                cp.ExStyle |= 0x02000000;
                //if (this.IsXpOr2003 == true)
                {
                    cp.ExStyle |= 0x00080000;
                    this.Opacity = 1;
                }
                return cp;
            }
        }

        private Boolean IsXpOr2003
        {
            get
            {
                OperatingSystem os = Environment.OSVersion;
                Version vs = os.Version;
                if (os.Platform == PlatformID.Win32NT)
                    if ((vs.Major == 5) && (vs.Major != 0))
                        return true;
                    else
                        return false;
                else
                    return false;

            }
        }

        #endregion




        private void Main_Load(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(UserName))
            {
                var onLineStat = UserName.IndexOf("管理员") > -1 ? "(离线)" : "(在线)";
                if (UserName.IndexOf("管理员")>-1)
                {
                    TsmUser.Text = UserName + onLineStat;
                }
                else
                {
                    TsmUser.Text = UserName + onLineStat;
                }
            }

            LoadMenuShowOrVisible(UserID);

            //调用封装的写入日志方法
            PageDataDto.SystemLogInfoAdd("工作台", "进入了工作台模块");
        }

        /// <summary>
        /// 工作台
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TsmiWork_Click(object sender, EventArgs e)
        {
            OpenChildFrom("Work");
            //调用封装的写入日志方法
            PageDataDto.SystemLogInfoAdd("工作台", "进入了工作台模块");
        }

        /// <summary>
        /// 产品
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TsmiProduct_Click(object sender, EventArgs e)
        {
            OpenChildFrom("ProductView");
            //调用封装的写入日志方法
            PageDataDto.SystemLogInfoAdd("产品", "进入了产品模块");
        }

        /// <summary>
        /// 记录
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TsmiRecord_Click(object sender, EventArgs e)
        {
            OpenChildFrom("TestRecords");
            //调用封装的写入日志方法
            PageDataDto.SystemLogInfoAdd("记录", "进入了记录模块");
        }

        /// <summary>
        /// 曲线
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TsmiCurve_Click(object sender, EventArgs e)
        {
            OpenChildFrom("Passage");
            //调用封装的写入日志方法
            PageDataDto.SystemLogInfoAdd("曲线", "进入了曲线模块");
        }

        /// <summary>
        /// 系统设置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsmiSet_Click(object sender, EventArgs e)
        {
            OpenChildFrom("Setting");
            //调用封装的写入日志方法
            PageDataDto.SystemLogInfoAdd("设置", "进入了系统设置模块");
        }


        /// <summary>
        /// 用户
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TsmSystem_Click(object sender, EventArgs e)
        {

            OpenChildFrom("SystemManager");
            //调用封装的写入日志方法
            PageDataDto.SystemLogInfoAdd("用户", "进入了用户管理模块");
        }

        /// <summary>
        /// MES控制面板
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TsmMES_Click(object sender, EventArgs e)
        {

            OpenChildFrom("MESControl");
            //调用封装的写入日志方法
            PageDataDto.SystemLogInfoAdd("MES控制面板", "进入了MES控制面板模块");
        }



        /// <summary>
        /// 点菜单 打开子窗体 传子窗体名 是否强制刷新页面
        /// </summary>
        /// <param name="childFromName"></param>
        /// <returns></returns>
        private void OpenChildFrom(string childFromName, bool bIsReLoad = false)
        {


            bool bHave = false;
            //子窗体已存在 则打开
            foreach (Form formChild in this.MdiChildren)
            {
                if (formChild.Name == childFromName)
                {
                    ////关闭，不关闭切换用户时无法更新页面控件
                    //formChild.Close();
                    //bHave = false;

                    formChild.MdiParent = this;
                    formChild.Activate();
                    formChild.StartPosition = FormStartPosition.Manual;
                    formChild.Dock = DockStyle.Fill;
                    //formChild.Parent = this.PanelMain;
                    formChild.Show();
                    bHave = true;

                }
                else
                {
                    formChild.Hide();
                }
            }
            //子窗体不存在 创建并打开
            if (bIsReLoad || bHave == false)
            {
                Form formChild = InitializeFormByName(childFromName);
                if (formChild != null)
                {
                    formChild.MdiParent = this;
                    formChild.Dock = DockStyle.Fill;
                    //formChild.Parent = this.PanelMain;
                    formChild.StartPosition = FormStartPosition.Manual;
                    formChild.Show();
                }
            }
        }

        /// <summary>
        /// 用窗体名称字符串 初始化一个窗体
        /// </summary>
        /// <param name="formName"></param>
        /// <returns></returns>
        public static Form InitializeFormByName(string formName)
        {
            // 字符串是完整的类名，包括命名空间 例 LiJu.Work
            try
            {
                // 使用反射创建窗体实例
                Type formType = Type.GetType("LiJu." + formName);
                if (formType != null)
                {
                    return (Form)Activator.CreateInstance(formType);
                }
            }
            catch (Exception ex)
            {
                // 处理异常，例如类型未找到或创建实例失败
                Console.WriteLine("Error: " + ex.Message);
            }
            return null;
        }

        /// <summary>
        /// 窗体关闭时事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Main_FormClosing(object sender, FormClosingEventArgs e)
        {
            Liju.Common.UnifiedObj.WriteLog(1, "程序退出\r\n");

            // 写入配置
            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            config.AppSettings.Settings["IsMesUserLogin"].Value = "0";
            config.AppSettings.Settings["IsLocalUserLogin"].Value = "0";

            config.Save(ConfigurationSaveMode.Modified);

            // 强制刷新配置
            ConfigurationManager.RefreshSection("appSettings");

            e.Cancel = true;

            // 关闭当前页面
            this.Hide();

            // 终止整个应用程序的运行
            Environment.Exit(Environment.ExitCode);
        }

        /// <summary>
        /// 退出主页面，回到登录页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TsmExit_Click(object sender, EventArgs e)
        {
            this.Hide();

            //调用封装的写入日志方法
            PageDataDto.SystemLogInfoAdd("退出", "退出了主页面，回到登录页");

            SignIn signIn = new SignIn();
            signIn.Show(); // 显示首页表单
        }

        /// <summary>
        /// 切换用户
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TsmSwitch_Click(object sender, EventArgs e)
        {
            // 创建子窗体实例
            UserSwitch userSwitch = new UserSwitch
            {
                //切换登录
                OperateType = 1
            };


            //调用封装的写入日志方法
            PageDataDto.SystemLogInfoAdd("切换用户", "操作了切换用户功能");

            // 显示子窗体并获取返回值
            var userInfo = ShowUserSwitchAndGetReturnValue(userSwitch);

            if (!string.IsNullOrWhiteSpace(userInfo.UserName))
            {
                var onLineStat = userInfo.UserName.IndexOf("管理员") > -1 ? "(离线)" : "(在线)";

                TsmUser.Text = userInfo.UserName + onLineStat;
                //更新页面功能元素
                LoadMenuShowOrVisible(userInfo.UserID);


                //调用封装的写入日志方法
                PageDataDto.SystemLogInfoAdd("切换用户", "切换用户成功！当前用户名：" + userInfo.UserName);


                //切换到首页
                OpenChildFrom("Work", true);
            }



        }


        /// <summary>
        /// 获取切换用户后的返回值
        /// </summary>
        /// <param name="subForm"></param>
        /// <returns></returns>
        private SwitchUserInfo ShowUserSwitchAndGetReturnValue(UserSwitch userSwitch)
        {
            // 显示子窗体
            userSwitch.ShowDialog();

            // 获取子窗体的返回值

            SwitchUserInfo switchUserInfo = new SwitchUserInfo()
            {
                UserID = userSwitch.ReturnID,
                UserName = userSwitch.ReturnValue
            };
            return switchUserInfo;
        }

        /// <summary>
        /// 更新密码
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TsmUpPwd_Click(object sender, EventArgs e)
        {
            // 创建子窗体实例
            UserSwitch userSwitch = new UserSwitch
            {
                //修改密码
                OperateType = 2,
                ReturnValue = UserName
            };


            //调用封装的写入日志方法
            PageDataDto.SystemLogInfoAdd("更新密码", "操作了更新密码功能");

            userSwitch.ShowDialog();
        }

        private void ScrewParamToolStripMenuItem_Click(object sender, EventArgs e)
        {

            PageDataDto.SystemLogInfoAdd("参数", "进入了参数管理模块");
            OpenChildFrom("ParameterManager3");
        }

        /// <summary>
        /// 页面加载时控制页面控件
        /// </summary>
        /// <param name="userID">用户编号</param>
        public void LoadMenuShowOrVisible(string userID)
        {
            //工作台
            this.tsmiWork.Visible = false;
            //产品
            this.tsmiProduct.Visible = false;
            //记录
            this.tsmiRecord.Visible = false;
            //曲线
            this.tsmiCurve.Visible = false;
            //MES控制面板
            this.TsmMES.Visible = false;


            //设置
            this.tsmiSet.Visible = false;

            //系统
            this.TsmSystem.Visible = false;
            //参数
            this.ScrewParamToolStripMenuItem.Visible = false;

            if (Liju.Common.MES.MesCheckPass)
            {
                this.TsmUpPwd.Visible = false;
            }

            //页面元素
            //获取当前页面功能
            var menuRole = PageDataDto.SystemMenuRoleInfo();

            if (Liju.Common.MES.MesCheckPass || menuRole.Work || userID == "admin")
            {
                this.tsmiWork.Visible = true;
            }
            if (Liju.Common.MES.MesCheckPass || menuRole.ProductView || userID == "admin")
            {
                this.tsmiProduct.Visible = true;
            }
            if (Liju.Common.MES.MesCheckPass || menuRole.TestRecords || userID == "admin")
            {
                this.tsmiRecord.Visible = true;
            }
            //if (Liju.Common.MES.MesCheckPass || menuRole.MESControl || userID == "admin")
            //{
            //    this.TsmMES.Visible = true;
            //}
            if (menuRole.Passage || userID == "admin")
            {
                this.tsmiCurve.Visible = true;
            }
            if (menuRole.SetUp || userID == "admin")
            {
                this.tsmiSet.Visible = true;
            }
            if (menuRole.SystemManager || userID == "admin")
            {
                this.TsmSystem.Visible = true;
            }
            if (menuRole.ParameterManager || userID == "admin")
            {
                this.ScrewParamToolStripMenuItem.Visible = true;
            }

        }


        private void PanelExit_Click(object sender, EventArgs e)
        {

            // 关闭当前页面
            this.Hide();

            // 终止整个应用程序的运行
            Environment.Exit(Environment.ExitCode);
        }

        private void PanelSx_Click(object sender, EventArgs e)
        {
            this.WindowState = FormWindowState.Minimized;
        }


    }
}
